package com.atguigu.gmall.cart.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.feign.GmallPmsClient;
import com.atguigu.gmall.cart.mapper.CartMapper;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import sun.awt.SunHints;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class CartListener {
    @Autowired
    GmallPmsClient pmsClient;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CartMapper cartMapper;
    private static final String PRICE_PREFIX = "cart:price:";
    private final static String KEY_PREFIX = "cart:info:";
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("cart_price-queue"),
            exchange = @Exchange(value = "PMS_SPU_EXCHANGE",
                    ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = "spu_price.update"
    ))
    public void asyncPrice(Long spuId, Message message, Channel channel) throws IOException {
        //如果为空，则直接确认
        if (spuId==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        //如果不为空，查询对应的spu的所有sku的信息，并将其价格缓存到redis
            ResponseVo<List<SkuEntity>> listResponseVo = pmsClient.querySkuBySpuId(spuId);
            List<SkuEntity> skuEntities = listResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuEntities)){
                skuEntities.forEach(skuEntity -> {
                    this.redisTemplate.opsForValue().set(PRICE_PREFIX+skuEntity.getId(),skuEntity.getPrice().toString());
                });
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("order_cart_queue"),
            exchange = @Exchange(value = "ORDER_CREATE_EXCHANGE",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = "create_order"
    ))
    public void deleteCart(Map msg, Message message, Channel channel) throws IOException {
        if (msg==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        try {
            String userId = msg.get("userId").toString();
            String skuIds = msg.get("skuIds").toString();
            List<String> skuids = JSON.parseArray(skuIds, String.class);
            if (StringUtils.isEmpty(userId)||CollectionUtils.isEmpty(skuids)){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }
            BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
            hashOps.delete(skuids.toArray());
            this.cartMapper.delete(new QueryWrapper<Cart>().eq("user_id",userId).in("sku_id",skuids));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }


    }

}
